import 'dart:ui';

import 'package:flame/components.dart';
import 'package:flame/flame.dart';
import 'package:flame/sprite.dart';
import 'package:flame_spine/flame_spine.dart';

class PlayerStateComponent2 extends SpriteAnimationComponent {
  //Image? _image;
  Vector2? pSize;
  var currentState = PlayState.IDLE;

  SpineComponent? _image;

  final states = [
    'walk',
    'aim',
    'death',
    'hoverboard',
    'idle',
    'jump',
    'portal',
    'run',
    'shoot',
  ];

  PlayerStateComponent2(Vector2 pSize) {
    this.pSize = pSize;
  }

  Future<void> initImage() async {
    print("加载图片");
    _image = await SpineComponent.fromAssets(
      atlasFile: 'assets/spineboy.atlas',
      skeletonFile: 'assets/spineboy-pro.skel',
      scale: Vector2(0.1, 0.1),
      anchor: Anchor.center,
      position: Vector2(size.x / 2, size.y / 2),
    );
    _image?.animationState.setAnimationByName(0, 'idle', true);
    await add(_image!);
  }


  @override
  Future<void> onLoad() async {
    debugMode = true;
    return super.onLoad();
  }

  bool isIdle(){
    return currentState == PlayState.IDLE;
  }
  bool isAttack(){
    return currentState == PlayState.ATTACK;
  }
  bool isRun(){
    return currentState == PlayState.RUN;
  }

  void resetState() async {
    currentState = PlayState.IDLE;
  }
  void loadIdleState(double stepTime) async {
    if (_image == null) {
      await initImage();
    }
    currentState = PlayState.IDLE;
    _image?.animationState.setAnimationByName(0, 'idle', true);
  }

  void loadAttackState(double stepTime) async {
    if (_image == null) {
      await initImage();
    }
    if (currentState == PlayState.ATTACK) {
      return;
    }
    currentState = PlayState.ATTACK;
    _image?.animationState.setAnimationByName(0, 'shoot', true);
  }

  void loadRunState(double stepTime) async {
    if (_image == null) {
      await initImage();
    }
    if (currentState == PlayState.RUN) {
      return;
    }
    currentState = PlayState.RUN;
    _image?.animationState.setAnimationByName(0, 'run', true);
  }

  @override
  void onRemove() {
    _image?.dispose();
  }
}

enum PlayState {
  IDLE,
  ATTACK,
  RUN,
}